/**
 * @(#)FutureResult.java, Sep 12, 2012. 
 * 
 * Copyright 2012 Yodao, Inc. All rights reserved.
 * YODAO PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.buaaer.mina;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author wangheng
 *
 */
public class FutureResult {
    
    private DataPackage object;

    private CountDownLatch latch = new CountDownLatch(1);
    
    public void finish(DataPackage object) {
        latch.countDown();
        this.object = object;
    }
    
    /**
     * wait for the result forever
     * 
     * @return
     * @throws Exception
     */
    public DataPackage get() throws Exception {
        return get(Long.MAX_VALUE);
    }
    
    /**
     * wait until the specified waiting time elapses
     * 
     * @param timeout
     * @return
     * @throws Exception
     */
    public DataPackage get(long timeout) throws Exception  {
        return get(timeout, TimeUnit.MILLISECONDS);
    }
    
    /**
     * wait until the specified waiting time elapses
     * 
     * @param timeout
     * @param unit
     * @return
     * @throws Exception
     */
    public DataPackage get(long timeout, TimeUnit unit) throws Exception {
        latch.await(timeout, unit);
        Object obj = object.getObject();
        if(obj instanceof Exception) {
            System.out.println("throw exception in get");
            throw (Exception)obj;
        }
        return object;
    }
    
}
